﻿using System.Xml.Linq;

namespace Lightray.Hattrick.ChppLib.EntityTypes
{
    public class MatchParticipantStats
    {
        public Formation Formation { get; private set; }
        public TacticType TacticType { get; private set; }
        public SkillLevel TacticSkill { get; private set; }
        public TeamAttitude TeamAttitude { get; private set; }
        public MatchRating MidfieldRating { get; private set; }
        public MatchRating RightDefenceRating { get; private set; }
        public MatchRating CentralDefenceRating { get; private set; }
        public MatchRating LeftDefenceRating { get; private set; }
        public MatchRating RightAttackRating { get; private set; }
        public MatchRating CentralAttackRating { get; private set; }
        public MatchRating LeftAttackRating { get; private set; }
        public MatchRating IndirectSetPiecesDefence { get; private set; }
        public MatchRating IndirectSetPiecesAttack { get; private set; }       

        protected MatchParticipantStats() { }

        internal static MatchParticipantStats FromXml(XElement participantNode)
        {
            HattrickXmlReader reader = new HattrickXmlReader(participantNode);
            return new MatchParticipantStats()
            {
                Formation = reader.ReadFormation("Formation"),
                TacticType = reader.ReadTacticType("TacticType"),
                TacticSkill = reader.ReadSkill("TacticSkill"),
                TeamAttitude = reader.ReadTeamAttitude("TeamAttitude"),
                MidfieldRating = readRating(reader, "RatingMidfield"),
                RightDefenceRating = readRating(reader, "RatingRightDef"),
                CentralDefenceRating = readRating(reader, "RatingMidDef"),
                LeftDefenceRating = readRating(reader, "RatingLeftDef"),
                RightAttackRating = readRating(reader, "RatingRightAtt"),
                CentralAttackRating = readRating(reader, "RatingMidAtt"),
                LeftAttackRating = readRating(reader, "RatingLeftAtt"),
                IndirectSetPiecesDefence = readRating(reader, "RatingIndirectSetPiecesDef"),
                IndirectSetPiecesAttack = readRating(reader, "RatingIndirectSetPiecesAtt")
            };
        }

        private static MatchRating readRating(HattrickXmlReader reader, string name)
        {
            int combinedRatingValue = reader.ReadNumber(name) + 3;
            return new MatchRating((SkillLevel)(combinedRatingValue / 4),
                                   (SecondaryMatchRating)(combinedRatingValue % 4));
        }
    }
}
